package com.limh.base.utils

import android.graphics.Bitmap

import com.squareup.picasso.Transformation

/**
 * @function：
 * @author： limh
 * @date： 2018/11/1
 * Copyright @2018 Corpration Name
 */
class SizeTransform : Transformation {

    override fun transform(source: Bitmap): Bitmap {

        val targetWidth = ScreenUtils.getScreenWidth()
        Logs.d("SizeTransform", "source.getHeight()=" + source.height + ",source.getWidth()=" + source.width + ",targetWidth=" + targetWidth)

        if (source.width == 0) {
            return source
        }

        //如果图片小于设置的宽度，则返回原图
        //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
        val aspectRatio = source.height.toDouble() / source.width.toDouble()
        val targetHeight = (targetWidth * aspectRatio).toInt()
        return if (targetHeight != 0 && targetWidth != 0) {
            val result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false)
            if (result != source) {
                // Same bitmap is returned if sizes are the same
                source.recycle()
            }
            result
        } else {
            source
        }

    }

    override fun key(): String {
        return "transformation" + " desiredWidth"
    }
}
